package org.meluk.billboard.jpa.seabattle;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;

@Entity
public class Ship implements Serializable {

    public Ship() {
    }

    public Ship(List<SBPoint> points) {
        pointList.addAll(points);
    }
    private static long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @OneToMany(mappedBy = "ship")
    private List<SBPoint> pointList = new ArrayList<SBPoint>();
    @ManyToOne
    @JoinColumn(name = "board_id")
    private SBBoard board;
    private Boolean killed;

    public void addPoints(List<SBPoint> points) {
        for (SBPoint p : points) {
            if (!getPointList().contains(p)) {
                if (p.getShip() != null) {
                    p.getShip().getPointList().remove(p);
                }
                pointList.add(p);
                p.setShip(this);
            }
        }
    }

    /**
     * проверяет является ли корабель убитым
     */
    public Boolean isShipKilled() {
        if (killed != null && killed) {
            return Boolean.TRUE;
        }
        for (SBPoint point : pointList) {
            if (point.getIsAlive() != null && point.getIsAlive()) {
                return Boolean.FALSE;
            }
        }
        killed = Boolean.TRUE;
        return killed;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public List<SBPoint> getPointList() {
        return pointList;
    }

    public void setPointList(List<SBPoint> pointList) {
        this.pointList = pointList;
    }

    public SBBoard getBoard() {
        return board;
    }

    public void setBoard(SBBoard board) {
        this.board = board;
    }

    public Boolean getKilled() {
        return killed;
    }

    public void setKilled(Boolean killed) {
        this.killed = killed;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append(" Ship{  id=");
        builder.append(id);
        builder.append("  board=");
        builder.append(board);
        builder.append("  killed =");
        builder.append(killed);
        builder.append(" pointList={");
        for (SBPoint p : pointList) {
            builder.append("\n");
            builder.append(p.toString());
        }
        builder.append("}}");
        return builder.toString();

    }
}
